package cn.edu.dgut.exp03.controller;

import cn.edu.dgut.exp03.models.RegionStats;
import cn.edu.dgut.exp03.services.RegionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class RegionController {

    //使用构造器注入RegionService
    private final RegionService regionService;

    public RegionController(RegionService regionService){
        this.regionService = regionService;
    }

    @GetMapping("/")
    public String home(Model model) {
        List<RegionStats> allStates;
        allStates = regionService.getAllRegionStats();
        //统计所有确诊总数
        int totalReportedCases=allStates.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        //统计相较于前一天增加的确诊病例数
        int totalNewCases=allStates.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats",allStates);
        model.addAttribute("totalReportedCases",totalReportedCases);
        model.addAttribute("totalNewCases",totalNewCases);
        //获取当天日期
        model.addAttribute("localDateTime", LocalDateTime.now());

        return "index";
    }
    @GetMapping("/{country}")
    public String country(Model model, @PathVariable("country") String country){

        List<RegionStats> allStates;
        if (country == null || country.equals("all"))
            allStates = regionService.getAllRegionStats();
        else
            allStates = regionService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStates -> locationStates.getCountry().equals(country))
                    .collect(Collectors.toList());

        //设置查询条件
        model.addAttribute("country", country);

        //统计所有确诊总数
        int totalReportedCases=allStates.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        //统计相较于前一天增加的确诊病例数
        int totalNewCases=allStates.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats",allStates);
        model.addAttribute("totalReportedCases",totalReportedCases);
        model.addAttribute("totalNewCases",totalNewCases);
        //获取当天日期
        model.addAttribute("localDateTime", LocalDateTime.now());

        return "index";
    }
}
